package SceneUnit
{
	import BasicEngine.Dispatcher;
	import BasicEngine.EntityManager;
	import BasicEngine.MsgId;
	import BasicEngine.MsgManager;
	import DataStore.DataSource;
	import DataStore.ResourceManager;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.Scene;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.filters.ColorMatrixFilter;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.net.URLRequest;
	import flash.system.IME;
	import flash.utils.Dictionary;
	import Map.MapManager;
	import Player.AnimationEntData;
	import Player.AnimationProc;
	import Player.AnimationUnit;
	import Player.DataCenter;
	import Player.VisualEntData;
	import Player.VisualProc;

	public class SceneManager
	{
		public static var GameStage:Sprite;
		public static var AcceptStage:DisplayObject;
		public static var MainScene:PlayScene;
		
		public static var Thumbnails:Dictionary;
		public static var ThumbnailUrls:Array;
		public static  var RootDir:String;
		public static var Imgs:Vector.<String>;
		public static var MapNames:Vector.<String>;
		public static var loader:Loader;
		
		public static var clrArray:Dictionary = new Dictionary();
		public static var tilesWidth:int = 23;
		public static var tilesHeight:int = 6;
		public static var clr:int = 0;
		public static var thumbnailReady:Boolean = false;
		
		public static var SceneID:int;
		public static var MapId:int;
		
		public static var CurrentId:int = -1;
		
		//场景循环是否进行
		public static var PauseUpdate:Boolean = false;
		
		public function SceneManager()
		{
		}		
		
		public  static function AddStaticEnt(_frames:Array,_x:int,_y:int,_layerIndex:int,_name:String="",_xOffset:int = 0,_yOffset:int = 0):int
		{
			var id:int  = EntityManager.CreateEntityWithID(SceneID, _name);
			var data:VisualEntData = new VisualEntData(id);
			DataCenter.Add(id,data);
			data.Name = _name +"_"+id.toString();
			data.X = _x;
			data.Y = _y;
			var layer:Sprite = (MainScene as PlayScene).Layers[_layerIndex];
			data.Init(_frames);		
			layer.addChild(data.ImgContainer);
			data.ImgContainer.x = data.X;
			data.ImgContainer.y = data.Y;
			return id;
		}
		
		/**
		 * 创建了实体,和实体数据,并通过ID,将两者联系在一起
		 */
		public static function AddAnimationEnt(_frames:Array, _x:int, _y:int, _layerIndex:int, _name:String = ""):int
		{
			var id:int = EntityManager.CreateEntityWithID(SceneID, _name);
			var data:AnimationEntData = new AnimationEntData(id);
			DataCenter.Add(id, data);
			data.Name = _name +"_"+id.toString();
			data.X = _x;
			data.Y = _y;
			var layer:Sprite = (MainScene as PlayScene).Layers[_layerIndex];
			data.Init(_frames);			
			layer.addChild(data.ImgContainer);
			data.ImgContainer.x = data.X;
			data.ImgContainer.y = data.Y;
			return id;
		}	
		
		
		//删除实体
		//一个实体要干净彻底的删除掉 (1)实体树(字典) (2)实体数据库(3)全局消息处理表
		public static function RemoveEnt(_id:int):void
		{
			var data:VisualEntData = DataCenter.GetData(_id);
			if(data != null)
			    data.DeActive();
			delete EntityManager.EntityIndexes[_id];
			DataCenter.Remove(_id);
			MsgManager.RemoveGlobalEntProc(_id);
		}			
		
		//场景管理器初始化
		//载入缩略图
		public static function Init(_root:Sprite,_stage:DisplayObject):void
		{
			InitClrArray();			
			GameStage = _root;				
			AcceptStage = _stage;
			RootDir = DataSource.thunbnailDir;
			Thumbnails = new Dictionary();
			ThumbnailUrls = DataSource.thumbnails;
			Imgs = new Vector.<String>();
			MapNames = new Vector.<String>();			
			for each(var item:Array in ThumbnailUrls)
			{
				MapNames.push(item[0]);
				Imgs.push(RootDir + item[1]);			
			}
			loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, OnLoadImg);
			LoadStep();			
			SetParent(new PlayScene(720, 220, 300, 300), _root);
			
			SceneID = EntityManager.CreateEntityWithID(EntityManager.RootId, "游戏场景");		
			RegistEntProc();
			
			//游戏循环开始启动
			Dispatcher.RegistTaskUnit(1, 10, 8, 0, "Update", function():void {
								MsgManager.SendMessage(new MsgId("场景循环消息", 0,SceneID, DataSource.MsgMins["Update"], 100));
			});			
			//初始化键盘事件
			InitKeyMouse();
		}		
		
		public static function LoadStep():void
		{
			if (Imgs.length == 0)
			{
				loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, OnLoadImg);	
				thumbnailReady = true;
				return;
			}
			var task:String = Imgs.shift();
			loader.name = MapNames.shift();
			loader.load(new URLRequest(task));			
		}
		
		public static function OnLoadImg(e:Event):void
		{
			var loader2:Loader = (e.target.loader) as Loader;			
			var bmpData:BitmapData = (loader2.content as Bitmap).bitmapData;
			Thumbnails[loader2.name] = bmpData;
			LoadStep();
		}
		
		public static function DeActinve():void
		{
			MainScene.DeActive();			
			GameStage.removeChild(MainScene);
		}	
		
		//缩略图资源是否准备好
		public static function GetFlag():Boolean
		{
			return thumbnailReady;
		}		
		
		public static function RemoveHandler(_id:int):void
		{
			var data:VisualEntData = DataCenter.GetData(_id);			
		}
		
		public static function AddOneSolider(_soliderType:String,_x:int,_y:int):void
		{
			var idPlayer:int = AddSolider(_soliderType, _x, _y);
			MsgManager.RegistIDProc(idPlayer, DataSource.MsgMins["SwitchAnimation"], AnimationProc.Instance.SwitchAnimation);
			
			AddHandler(idPlayer, MouseEvent.MOUSE_OVER, function(e:MouseEvent):void
			{
				var aMatrix:Array = [2, 0, 0, 0, 0,
				                     0, 2, 0, 0, 0,
									 0, 0, 2, 0, 0, 
									 0, 0, 0, 1, 0];
				var data:VisualEntData = DataCenter.GetData(idPlayer);
				var filter:ColorMatrixFilter = new ColorMatrixFilter(aMatrix);
				data.ImgContainer.filters = [filter];
			});
			
			
			AddHandler(idPlayer, MouseEvent.MOUSE_OUT, function(e:MouseEvent):void
			{
				var data:VisualEntData = DataCenter.GetData(idPlayer);
				data.ImgContainer.filters = null;
				
			});
			AddHandler(idPlayer, MouseEvent.CLICK, function(e:MouseEvent):void
			{
				var data:AnimationEntData = DataCenter.GetData(idPlayer) as AnimationEntData;
				SceneManager.CurrentId = data.ID;
			});
			
			AddHandler(idPlayer, MouseEvent.MOUSE_DOWN, function(e:MouseEvent):void
			{
			});
		}
		
		private static function InitKeyMouse():void
		{
			IME.enabled = false;
			AcceptStage.addEventListener(KeyboardEvent.KEY_DOWN, function (e:KeyboardEvent):void
			{
			    MsgManager.SendMessage(new MsgId("KeyDownMsg", 0, SceneID,DataSource.MsgMins["KeyDown"], e.keyCode));
			});
			AcceptStage.addEventListener(KeyboardEvent.KEY_UP, function (e:KeyboardEvent):void
			{
			    MsgManager.SendMessage(new MsgId("KeyUpMsg", 0, SceneID,DataSource.MsgMins["KeyUp"], e.keyCode));
			});
			AcceptStage.addEventListener(MouseEvent.CLICK, function(e:MouseEvent):void
			{
				if (CurrentId != -1)
				{
					var data:AnimationEntData = DataCenter.GetData(CurrentId) as AnimationEntData;
					var destinationPoint:Point = new Point(e.stageX, e.stageY);
					data.target = destinationPoint;
					data.move = true;
				}
			});
		}
		
		private static function SetParent(_scene:PlayScene,_parent:Sprite):void
		{
			GameStage = _parent;
			MainScene = _scene;
		     _parent.addChild(_scene);	
		}
		
		private static function  InitClrArray():void
		{
			for (var i:int = 0; i < tilesWidth; i++)
			{
				for (var j:int = 0; j < tilesHeight; j++)
				{
					var pos:String = i.toString() + "-" + j.toString();
					clr += 10;	
					clrArray[pos] = clr;
				}
			}
		}
		
		private static function RegistEntProc():void
		{
			MsgManager.RegistIDProc(SceneID, DataSource.MsgMins["Update"], SceneProc.Update);	
			MsgManager.RegistIDProc(SceneID, DataSource.MsgMins["KeyDown"], SceneProc.KeyDown);
			MsgManager.RegistIDProc(SceneID, DataSource.MsgMins["KeyUp"], SceneProc.KeyUp);
		}
		
		/**
		 * 为VisualEnt添加事件处理
		 */
		private static function AddHandler(_id:int, _event:String, _handler:Function):void
		{
			var data:VisualEntData = DataCenter.GetData(_id);
			data.ImgContainer.addEventListener(_event, _handler);
			data.AddHandler(_event, _handler);
		}
		
		private static function AddSolider(_type:String,_x:int,_y:int):int
		{
			var n:int =   DataSource.GetSoliderType(_type);
			var frams:Array = new Array();
			for (var i:int = 0; i < 28; i++)
				{
			     	frams.push(ResourceManager.SoliderPool[n][i]);
					var dd:Dictionary = ResourceManager.SoliderPool;
			    }	
			var id:int = AddAnimationEnt(frams, _x, _y, 0, "");
			var data:AnimationEntData = (AnimationEntData)(DataCenter.GetData(id));
			
			var standNorth:AnimationUnit = new AnimationUnit("StandNorth", 200);
			standNorth.AddFrameData(0, 0, 19, 0);
			data.AddAnimationUnit(standNorth);
			
			var standSouth:AnimationUnit = new AnimationUnit("StandSouth", 200);
			standSouth.AddFrameData(0, 0, 18, 0);
			data.AddAnimationUnit(standSouth);
			
			var standWest:AnimationUnit = new AnimationUnit("StandWest", 1900);
			standWest.AddFrameData(0, 0, 20, 0);
			standWest.AddFrameData(0, 0, 25, 0);
			data.AddAnimationUnit(standWest);
			
			var standEast:AnimationUnit = new AnimationUnit("StandEast", 1900);
			standEast.AddFrameData(0, 0, 20, 1);
			standEast.AddFrameData(0, 0, 25, 1);
			data.AddAnimationUnit(standEast);
			
			
			var moveNorth:AnimationUnit = new AnimationUnit("MoveNorth", 200);
			moveNorth.AddFrameData(0, 0, 19, 0);
			moveNorth.AddFrameData(0, 0, 14, 0);
			moveNorth.AddFrameData(0, 0, 19, 0);
			moveNorth.AddFrameData(0, 0, 15, 0);
			data.AddAnimationUnit(moveNorth);
			
			var moveSouth:AnimationUnit = new AnimationUnit("MoveSouth", 200);
			moveSouth.AddFrameData(0, 0, 18, 0);
			moveSouth.AddFrameData(0, 0, 12, 0);
			moveSouth.AddFrameData(0, 0, 18, 0);
			moveSouth.AddFrameData(0, 0, 13, 0);
			data.AddAnimationUnit(moveSouth);
			
			var moveWest:AnimationUnit = new AnimationUnit("MoveWest", 180);
			moveWest.AddFrameData(0, 0, 20, 0);
			moveWest.AddFrameData(0, 0, 16, 0);
			moveWest.AddFrameData(0, 0, 20, 0);
			moveWest.AddFrameData(0, 0, 17, 0);
			data.AddAnimationUnit(moveWest);
			
			var moveEast:AnimationUnit = new AnimationUnit("MoveEast", 180);
			moveEast.AddFrameData(0, 0, 20, 1);
			moveEast.AddFrameData(0, 0, 16, 1);
			moveEast.AddFrameData(0, 0, 20, 1);
			moveEast.AddFrameData(0, 0, 17, 1);
			data.AddAnimationUnit(moveEast);
			
			var Weary:AnimationUnit = new AnimationUnit("Weary", 800);
			Weary.AddFrameData(0, 0, 21, 1);
			Weary.AddFrameData(0, 0, 22, 1);
			data.AddAnimationUnit(Weary);
			
			var Happy:AnimationUnit = new AnimationUnit("Happy", 400);
			Happy.AddFrameData(0, 0, 18, 1);
			Happy.AddFrameData(0, 0, 27, 1);
			data.AddAnimationUnit(Happy);
			
			var Hurt:AnimationUnit = new AnimationUnit("Hurt", 400);
			Hurt.AddFrameData(0, 0, 26, 1);
			data.AddAnimationUnit(Hurt);
	
			var ParryNorth:AnimationUnit = new AnimationUnit("ParryNorth", 400);
			ParryNorth.AddFrameData(0, 0, 24, 1);
			data.AddAnimationUnit(ParryNorth);
			
			var ParrySouth:AnimationUnit = new AnimationUnit("ParrySouth", 400);
			ParrySouth.AddFrameData(0, 0, 23, 1);
			data.AddAnimationUnit(ParrySouth);
			
			var ParryWest:AnimationUnit = new AnimationUnit("ParryWest", 400);
			ParryWest.AddFrameData(0, 0, 25, 0);
			data.AddAnimationUnit(ParryWest);
			
			var ParryEast:AnimationUnit = new AnimationUnit("ParryEast", 400);
			ParryEast.AddFrameData(0, 0, 25, 1);
			data.AddAnimationUnit(ParryEast);
			
			var AtkNorth:AnimationUnit = new AnimationUnit("AtkNorth", 180);
			AtkNorth.AddFrameData(-10, -10, 4, 0);
			AtkNorth.AddFrameData(-10, -10, 5, 0);
			AtkNorth.AddFrameData(-10, -10, 6, 0);
			AtkNorth.AddFrameData(-10, -10, 7, 0);
			data.AddAnimationUnit(AtkNorth);
			
			var AtkSouth:AnimationUnit = new AnimationUnit("AtkSouth", 180);
			AtkSouth.AddFrameData(-10, -10, 0, 0);
			AtkSouth.AddFrameData(-10, -10, 1, 0);
			AtkSouth.AddFrameData(-10, -10, 2, 0);
			AtkSouth.AddFrameData(-10, -10, 3, 0);
			data.AddAnimationUnit(AtkSouth);
			
			var AtkWest:AnimationUnit = new AnimationUnit("AtkWest", 180);
			AtkWest.AddFrameData(-13, -8, 8, 0);
			AtkWest.AddFrameData(-13, -8, 9, 0);
			AtkWest.AddFrameData(-13, -8, 10, 0);
			AtkWest.AddFrameData(-13, -8, 11, 0);
			data.AddAnimationUnit(AtkWest);
			
			var AtkEast:AnimationUnit = new AnimationUnit("AtkEast", 180);
			AtkEast.AddFrameData(0, -8, 8, 1);
			AtkEast.AddFrameData(0, -8, 9, 1);
			AtkEast.AddFrameData(0, -8, 10, 1);
			AtkEast.AddFrameData(0, -8, 11, 1);
			data.AddAnimationUnit(AtkEast);
			
			data.AddUpdateProc(AnimationProc.Instance.UpdateFrame, "UpdateFrame");
			MsgManager.RegistIDProc(data.ID, DataSource.MsgMins["KeyDown"], AnimationProc.Instance.KeyDown);
			MsgManager.RegistIDProc(data.ID, DataSource.MsgMins["KeyUp"], AnimationProc.Instance.KeyUp);
			data.SwitchAnimation("AtkEast");
		    return id;
		}		
	}
}